Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cancel running jobs if possible when run Scheduler.StopJobs() #819

Merged

Conversation

27149chen
Copy link
Contributor

@27149chen 27149chen commented Jan 23, 2025

What does this do?

when run Scheduler.StopJobs(), the scheduler will wait for the running jobs to be completed. If there are long running jobs, it will always return "timed out waiting for jobs to finish".

This pr try to cancel the running jobs if possible

Which issue(s) does this PR fix/relate to?

Resolves #818

List any changes that modify/break current functionality

You can now add a task function which accept ctx as the first param, but you do need pass a ctx actually, gocron will handle it properly

	j, err := s.NewJob(
		gocron.DurationJob(
			10*time.Second,
		),
		gocron.NewTask(
			func(ctx context.Context) {
				// do things
			},
		),
	)

but if you have you own ctx, fell free to pass it

	j, err := s.NewJob(
		gocron.DurationJob(
			10*time.Second,
		),
		gocron.NewTask(
			func(ctx context.Context) {
				// do things
			},
                         ctx,
		),
	)

or you can also pass it as a job option to control the whole thing

	j, err := s.NewJob(
		gocron.DurationJob(
			10*time.Second,
		),
		gocron.NewTask(
			func(ctx context.Context) {
				// do things
			},
		),
                gocron.WithContext(ctx)
	)

Have you included tests for your changes?

yes

Did you document any new/modified functionality?

  • Updated example_test.go
  • Updated README.md

Notes

scheduler_test.go Outdated Show resolved Hide resolved
Copy link
Contributor

@JohnRoesler JohnRoesler left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @27149chen this is a great addition. Some things that will be needed still:

  • addition of the new method to example_test.go
  • additional comments on the NewJob and NewTask functions explaining that if your task accepts a context as it's first parameter, gocron will pass in a context you can listen to for cancellation. Also, updating the example_test.go for the NewTask

I will make a PR to address.

@JohnRoesler JohnRoesler merged commit 50966c7 into go-co-op:v2 Jan 23, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] - A long running job can not be cancelled when run s.StopJobs()
2 participants